import os,time
import requests
from urllib.parse import urlencode
from urllib.request import urlretrieve


def getPage(offset):
	'''爬取信息'''
	#定义参数
	params = {
	'tn': 'resultjson_com',
	'ipn': 'rj',
	'ct': '201326592',
	'is':'' ,
	'fp': 'result',
	'queryWord': '街拍',
	'cl': '2',
	'lm': '-1',
	'ie': 'utf-8',
	'oe': 'utf-8',
	'adpicid':'',
	'st': '-1',
	'z':'', 
	'ic': '0',
	'hd':'', 
	'latest':'',
	'copyright':'', 
	'word':'街拍',
	's':'', 
	'se':'', 
	'tab':'', 
	'width':'', 
	'height':'',
	'face': '0',
	'istype': '2',
	'qc':'', 
	'nc':'1',
	'fr':'', 
	'expermode':'', 
	'force':'', 
	'pn': offset,
	'rn': '30',
	'gsm': '1e',
	'1554788980532':'', 
	}
	#初始化url地址
	url = "https://image.baidu.com/search/acjson?"+urlencode(params)
	#爬取数据
	try:
		res = requests.get(url)
		if res.status_code == 200:
			return res.json()   #以json格式返回
	except:
		return None

def getImage(json):
	'''获取图片信息'''
	data = json.get("data")
	if data:
		for item in data:
			image_list = item.get("replaceUrl",[])
			title = item.get("fromPageTitleEnc")
			for im in image_list:
				yield{
				'image':im.get('ObjURL'),
				'title':title,
				}


def saveImage(item):
	#储存图片信息
	#处理图片的储存路径
	path = os.path.join("./mypic/",item.get('title'))  #字典数据格式
	if not os.path.exists(path):
		os.mkdir(path)
	#图片路径拼装
	local_image_url = item.get('image')
	#字符串拆分
	save_pic = path+"/"+local_image_url.split("/").pop()+".jpg"

	#储存图片
	urlretrieve(local_image_url,save_pic)

def main(offset):
	json = getPage(offset)   #json数据
	for item in getImage(json):
		#获取一条数据
		print(item)
		saveImage(item)



if __name__=="__main__":
	for i in range(2):
		main(offset = i*30)
		time.sleep(1)
